﻿namespace Journey.Data.Users
{
    using Journey.Data.EntityFramework;
    using Journey.Security;
    using System.Data.Entity;

    /// <summary>
    /// 用户数据映射。
    /// </summary>
    public class UserConfigurationMapper : IConfigurationMapper
    {
        /// <summary>
        /// 执行映射。
        /// </summary>
        /// <param name="modelBuilder">实体模型绑定器。</param>
        public void Execute(DbModelBuilder modelBuilder)
        {
            modelBuilder.Ignore<AnonymousUser>();

            modelBuilder.Entity<User>().ToTable("journey_users");
            modelBuilder.Entity<User>().HasKey(u => u.Id);
            modelBuilder.Entity<User>().Property(u => u.Name).HasMaxLength(50).IsRequired();
            modelBuilder.Entity<User>().Property(u => u.Email).HasMaxLength(150).IsRequired();

            modelBuilder.ComplexType<Account>().Property(account => account.AccountNumber).HasColumnName("AccountNumber").HasMaxLength(20).IsRequired();
            modelBuilder.ComplexType<Account>().Property(account => account.Password).HasColumnName("Password").HasMaxLength(32).IsRequired();

            modelBuilder.Entity<User>().HasMany(u => u.Roles);
            modelBuilder.Entity<User>().HasMany(u => u.Roles).WithMany().Map(map =>
            {
                map.ToTable("journey_userRoles");
                map.MapLeftKey("userId");
                map.MapRightKey("roleId");
            });

            modelBuilder.Entity<Role>().ToTable("journey_roles");
            modelBuilder.Entity<Role>().HasKey(role => role.Id);
            modelBuilder.Entity<Role>().Property(role => role.Name).HasMaxLength(50).IsRequired();
            modelBuilder.Entity<Role>().Property(role => role.DisplayName).HasMaxLength(50).IsRequired();

            modelBuilder.Entity<Role>().HasMany(role => role.Permissions).WithMany().Map(map =>
            {
                map.ToTable("journey_rolePermissions");
                map.MapLeftKey("roleId");
                map.MapRightKey("permissionId");
            });

            modelBuilder.Entity<Permission>().ToTable("journey_permissions");
            modelBuilder.Entity<Permission>().HasKey(p => p.Id);
            modelBuilder.Entity<Permission>().Property(p => p.Name).HasMaxLength(50).IsRequired();
            modelBuilder.Entity<Permission>().Property(p => p.Description).HasMaxLength(50).IsRequired();
        }
    }
}